package br.com.fiap.beans;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.beanutils.BeanUtils;

import br.com.fiap.dao.TrechoDAO;
import br.com.fiap.dao.VooDAO;
import br.com.fiap.entity.Trecho;
import br.com.fiap.entity.Voo;

@Named
@ManagedBean
@SessionScoped
public class TrechoBean extends AbstractBeanAcessor implements Serializable {

	private static final long serialVersionUID = 2097952383235505194L;
	
	private Trecho trecho = new Trecho();
	private Integer numeroVoo;
	
	@Inject
	private TrechoDAO trechoDAO;
	
	@Inject
	private VooDAO vooDAO;

	public Trecho getTrecho() {
		
		if (trecho.getVoo() == null) {
			trecho.setVoo(new Voo());
		}
		
		return trecho;
	}

	public void setTrecho(Trecho trecho) {
		this.trecho = trecho;
	}
	
	public Integer getNumeroVoo() {
		return numeroVoo;
	}

	public void setNumeroVoo(Integer numeroVoo) {
		this.numeroVoo = numeroVoo;
	}

	public List<SelectItem> getVoos() {
		
		List<Voo> voos = vooDAO.findByNumero(null);
		
		List<SelectItem> itemsVoo = new LinkedList<SelectItem>();
		
		for (Voo voo : voos) {
			itemsVoo.add(new SelectItem(voo.getNumero(), voo.getNumero().toString()));
		}
		
		return itemsVoo;
	}

	public String novoTrecho() {
		this.trecho = new Trecho();
		
		return "/trecho/cadastro-trecho";
	}
	
	public String  salvarDados() {
		
		trechoDAO.saveOrUpdate(this.trecho);
		
		this.trecho = new Trecho();
		
		return "/trecho/sucesso-alteracao";
		
	}
	
	public String recuperarVoo(Long id) {
		Trecho persistedTrecho = trechoDAO.findById(id);
		
		try {
			BeanUtils.copyProperties(trecho, persistedTrecho);
		} catch (IllegalAccessException e) {
			System.out.println("Erro copyProperties.");
		} catch (InvocationTargetException e) {
			System.out.println("Erro copyProperties.");
		}
		
		return "/trecho/cadastro-techo";
	}
	
}
